package com.gcu.common.base.result;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.gcu.common.base.entity.PageResult;
import lombok.Data;

import java.io.Serializable;
import java.util.List;

/**
 * @ system:Mac
 * @ author:lin tingfeng
 * @ data:2023/9/20 13:54
 * @ package_name:com.gcu.common.base.result
 * @ project_name:SpringCloud-Oauth2
 * @ desc: 统一结果集
 */
@Data
@JsonInclude(JsonInclude.Include.NON_NULL)
public class SysResult<T> implements Serializable {

    private String code;

    private T data;

    private String msg;

    private Long total;

    public static <T> SysResult<T> ok() {
        return ok(null);
    }

    public static <T> SysResult<T> ok(T data) {
        SysResultCode rce = SysResultCode.SUCCESS;
        if (data instanceof Boolean && Boolean.FALSE.equals(data)) {
            rce = SysResultCode.SYSTEM_EXECUTION_ERROR;
        }
        return result(rce, data);
    }

    public static <T> SysResult<T> failed() {
        return result(SysResultCode.SYSTEM_EXECUTION_ERROR.getCode(), SysResultCode.SYSTEM_EXECUTION_ERROR.getMsg(), null);
    }

    public static <T> SysResult<T> failed(String msg) {
        return result(SysResultCode.SYSTEM_EXECUTION_ERROR.getCode(), msg, null);
    }

    public static <T> SysResult<T> judge(boolean status) {
        if (status) {
            return ok();
        } else {
            return failed();
        }
    }

    public static <T> SysResult<T> failed(ISysResultCode resultCode) {
        return result(resultCode.getCode(), resultCode.getMsg(), null);
    }

    public static <T> SysResult<T> failed(ISysResultCode resultCode, String msg) {
        return result(resultCode.getCode(), msg, null);
    }

    private static <T> SysResult<T> result(ISysResultCode resultCode, T data) {
        return result(resultCode.getCode(), resultCode.getMsg(), data);
    }

    private static <T> SysResult<T> result(String code, String msg, T data) {
        SysResult<T> result = new SysResult<>();
        result.setCode(code);
        result.setData(data);
        result.setMsg(msg);
        return result;
    }


    public static boolean isSuccess(SysResult<?> result) {
        return result != null && SysResultCode.SUCCESS.getCode().equals(result.getCode());
    }

    public static <T> SysResult page(PageResult<T> page) {
        SysResult<List<T>> result = new SysResult<>();
        result.setCode(SysResultCode.SUCCESS.getCode());
        result.setMsg(SysResultCode.SUCCESS.getMsg());
        result.setData(page.getList());
        result.setTotal(page.getTotal());
        return result;
    }
}
